<?php

class Admin_UserController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    /**
     * 后台用户首页
     *
     *
     */
    public function homeAction()
    {
        $modelUser = new Ms_Model_User();
        $users = $modelUser->getUsers();
        $this->view->users = $users;
    }

    /**
     * 添加用户
     *
     *
     */
    public function createAction()
    {
        $formUser = new Ms_Form_User();
        if ($this->getRequest()->isPost()){
            if ($formUser->isValid($_POST)){
                $data = $formUser->getValues();
                unset($data['password2']);
                $modelUser = new Admin_Model_User();
                $newUser = $modelUser->createUser($data);
                if ($newUser){
                    $this->_redirect('/admin/user/home');
                }
            }
        }
        $this->view->formUser = $formUser;
    }

    /**
     * 编辑用户信息
     *
     * 管理员在后台修改用户信息
     *
     * @throws Zend_Exception
     *
     *
     */
    public function editAction()
    {
        $id = $this->_request->getParam('id');
        $formUser = new Ms_Form_User();
        $formUser->removeElement('password2');
        $formUser->removeElement('avatar');
        $modelUser = new Ms_Model_User();
        if ($this->getRequest()->isPost()){
            if ($formUser->isValid($_POST)){
                $data = $formUser->getValues();
                $updateUser = $modelUser->updateUser($id, $data);
                
                if (updateUser){
                    $this->_redirect('/admin/user/home');
                }
            }
            
        }
        $user = $modelUser->find($id)->current();
        $formUser->populate($user->toArray());
        $this->view->formUser = $formUser;
    }

    /**
     * 删除用户
     *
     *
     */
    public function deleteAction()
    {
        $id = $this->_request->getParam('id');
        $modelUser = new Ms_Model_User();
        $modelUser->deleteUser($id);
        $this->_redirect('/admin/user/home');
    }

    /**
     * 用户详细信息页面
     *
     * 获取id参数传递给视图，由视图助手调用前台account页面
     *
     */
    public function viewAction()
    {
        // 视图页面由视图助手调用
        $this->view->id = $this->_request->getParam('id');
    }

    /**
     * 验证用户
     * 
     * 获取前台AJAX请求的数据并在数据库中进行查询                 
     * 判断是否已存在同名用户
     * 返回结果为布尔值ture或false
     */
    public function validateAction()
    {
        $this->_helper->layout()->disableLayout();
        
        if ($_POST['username']){
            $modelUser = new Ms_Model_User();
            $validUser = $modelUser->validUser($_POST['username']);
            if ($validUser){
                echo true;
            }
            else{
                echo false;
            }
        }
        else{
            echo false;
        }
    }


}



